package com.huixue.cn.ztej.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.Role;
import com.huixue.cn.ztej.bean.Section;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.bean.UserPassword;
import com.huixue.cn.ztej.constants.UserUtil;
import com.huixue.cn.ztej.enums.RoleStatus;
import com.huixue.cn.ztej.persistence.Domain;
import com.huixue.cn.ztej.service.SysPictureService;
import com.huixue.cn.ztej.service.SysProjectService;
import com.huixue.cn.ztej.service.SysRoleService;
import com.huixue.cn.ztej.service.SysSectionService;
import com.huixue.cn.ztej.service.SysUserService;
import com.huixue.cn.ztej.utils.MD5;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;
import com.huixue.cn.ztej.utils.annotation.RequestMappingName;
import com.huixue.cn.ztej.utils.framwork.PageParameter;

@Domain(User.class)
@Controller
@RequestMapping(value = "/sys/user")
public class UserController extends BaseController {

	
	@Autowired(required = true)
	SysUserService sysUserService;
	
	@Autowired(required = true)
	SysRoleService sysRoleService;

	@Autowired(required = true)
	SysProjectService sysProjectService;
	
	@Autowired(required = true)
	SysSectionService sysSectionService;
	
	@RequestMapping(value = "/saveUser")
	public String save(@ModelAttribute("user") User user) {
		user.setCreateTime(new Date());
		sysUserService.saveUser(user);
		return "/register";
	}
	
	@RequestMapping(value = "/listUser")
	public String list(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = PageParameter.DEFAULT_PAGE_SIZE+"") Integer rows,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		String searchUserName = request.getParameter("search_userName");
		Map<String, Object> searchParams = new HashMap<String,Object>();
		if(searchUserName!=null && searchUserName.trim().length()>0){
			searchParams.put("userName", searchUserName.trim());
			model.addAttribute("searchUserName", searchUserName);
		}
		
		User currentUser = (User)request.getSession().getAttribute("loginUser");
		if(currentUser.getRoleId()!=null && currentUser.getRoleId().equals(RoleStatus.ROLE_8.getRoleId()+"")){
			searchParams.put("proId", currentUser.getProjectID());
		}else{
			Results projectRes =  sysProjectService.findAll(searchParams);
			model.addAttribute("projectRes", projectRes);
		}
		
		String proejctId = request.getParameter("projectId");
		if(proejctId!=null && proejctId.trim().length()>0 && Integer.valueOf(proejctId) >0 ){
			searchParams.put("proId", proejctId);
			model.addAttribute("projectId", proejctId);
		}
		
		Results results =  sysUserService.searchUserByPage(searchParams,page,rows);	
		
		
		model.addAttribute("res", results);
		
		return "/user/list";
	}
	
	
	@RequestMappingName(value = "跳转到更新页面")
	@RequestMapping(value = "/toUpdate/{userId}")
	public String toUpdate(@PathVariable("userId")Integer userId,Model model,HttpServletRequest request) {
		Map<String, Object> searchParams = new HashMap<String,Object>();
		User currentUser = (User)request.getSession().getAttribute("loginUser");
		if(currentUser.getRoleId()!=null && currentUser.getRoleId().equals(RoleStatus.ROLE_8.getRoleId()+"")){
			searchParams.put("roleIds", new Integer[]{2,3,4,5,6,8});
			searchParams.put("proId", currentUser.getProjectID());
		}
		
		User user = sysUserService.findUserById(Integer.valueOf(userId));
		model.addAttribute("res", user);
		Results roleRs =  sysRoleService.searchRole(searchParams);
		model.addAttribute("roleRs", roleRs);
		
		Results projectRes =   sysProjectService.findAll(searchParams);
		model.addAttribute("projectRes", projectRes);
		
		List<Section> sectionList = sysSectionService.listSectionByPro(Integer.valueOf(user.getProjectID()));
		model.addAttribute("sectionRes", sectionList);
		
		//项目查询
		return "/user/update";
	}
	
	@RequestMappingName(value = "跳转到更新页面")
	@RequestMapping(value = "/update")
	public String update(@ModelAttribute("user") User userForm,Model model,HttpServletRequest request) {
		
		String userId = request.getParameter("user_id");		
		
		User user = sysUserService.findUserById(Integer.valueOf(userId));
		String roleId = request.getParameter("roleId");	
		String status = request.getParameter("status");	
		
		user.setRoleId(userForm.getRoleId());
		user.setStatus(userForm.getStatus());
		user.setLoginName(userForm.getLoginName());
		user.setUserName(userForm.getUserName());
		user.setProjectID(userForm.getProjectID());
		user.setSegmentID(userForm.getSegmentID());
		sysUserService.updateUser(user);
		
		return "redirect:/sys/user/toUpdate/"+user.getUser_id();
	}
	
	@RequestMapping(value = "/approve")
	public String approve(HttpServletRequest request,HttpServletResponse response,Model model) {
		String userId = request.getParameter("userId");
		User user = sysUserService.findUserById(Integer.valueOf(userId));
		user.setStatus(UserUtil.APPROVE_YES);
		sysUserService.updateUser(user);
		return "redirect:/sys/user/listUser";
	}
	
	@RequestMapping(value = "/resetPwd/{userId}",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	public Results resetPwd(@PathVariable("userId")Integer userId,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		User user = sysUserService.findUserById(userId);
		user.setPassword(MD5.md5("123456"));
		sysUserService.updateUser(user);
		Results results = new Results(
				API_RETURN_STATUS.NORMAL.value(),
				API_RETURN_STATUS.NORMAL.desc()
				);
		
		return results;
	}
	
	@ResponseBody
	@RequestMapping(value = "/toUpdatePwd",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	public Results toUpdatePwd(@RequestBody UserPassword user,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		User currentUser = (User)request.getSession().getAttribute("loginUser");
		if(!currentUser.getPassword().equals(MD5.md5(user.getOldPassword()))){
			Results results = new Results(
					API_RETURN_STATUS.PASSWORD_ERROR.value(),
					"原密码错误"
					);
			return results;
		}else{
			currentUser.setPassword(MD5.md5(user.getNewPassword()));
			sysUserService.updateUser(currentUser);
			Results results = new Results(
					API_RETURN_STATUS.NORMAL.value(),
					API_RETURN_STATUS.NORMAL.desc()
					);
			return results;
		}
	}
	
	
	@RequestMapping(value = "/updatePwd")
	public String updatePwd(HttpServletRequest request,HttpServletResponse response) {
		return "/user/updatepwd";
	}
	
	@ResponseBody
	@RequestMapping(value = "/disableUser/{userId}/{status}",produces="application/json;charset=UTF-8")
	public Results disableUser(@PathVariable("userId")Integer userId,@PathVariable("status")Integer status,
			HttpServletRequest request,HttpServletResponse response) {
		
		User user = sysUserService.findUserById(userId);
		user.setIsAvailable(status);
		sysUserService.updateUser(user);
		Results results = new Results(
				API_RETURN_STATUS.NORMAL.value(),
				API_RETURN_STATUS.NORMAL.desc()
				);
		
		return results;
	}
	
	
}
